<template>
    <div>
        <a-button type='primary' @click='addNew(null)'>{{$translate('add')}}</a-button>
    </div>
    <div class='m-t-10'>
        <XTable name-key='name' :columns='columns' :data='dataRows' row-key='id'>
            <template #status='{record}'>
                <a-tag v-if='record.status == 1' color='#87d068'>{{$translate('enable')}}</a-tag>
                <a-tag v-else>{{$translate('disable')}}</a-tag>
            </template>
            <template #$action='{record}'>
                <XTextButton @click='addNew(record)'>新增</XTextButton>
            </template>
        </XTable>   
    </div>
    <XDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close='close'>
        <XForm ref='formRef' :layout='langStore.locale == "zh" ? "horizontal" : "vertical"' :label-col='{span : langStore.locale == "zh" ? 5 : 24}' :fields='formFields'></XForm>
    </XDialog>
</template>

<script lang='ts' setup>
    import { computed, nextTick, ref } from "vue";
    import { message, Modal } from "ant-design-vue";
    import { deleteApi, listApi, optionsApi, saveApi } from "@/api/system/Department";
    import { recursionFn } from "@/utils";
    import { useAuthStore, useLangStore } from "@/store";

    const langStore = useLangStore()
    const authStore = useAuthStore()

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()


    const formFields:FormField[] = [
        {label : 'id', name : 'id', hidden : true},
        {label : langStore.translate('superDept'), name : 'parentId', required : true, type : 'treeSelect', options : getOptions, labelField : 'name', valueField : 'id', childrenField : 'children'},
        {label : langStore.translate('name'), name : 'name', required : true, maxlength : 30},
        {label : langStore.translate('leader'), name : 'leader', maxlength : 30},
        {label : langStore.translate('tel'), name : 'tel', maxlength : 11},
        {label : langStore.translate('sort'), name : 'sort', type : 'number'},
        {label : langStore.translate('status'), name : 'status', type : 'switch', attrs : {checkedChildren : langStore.translate("enable"), unCheckedChildren : langStore.translate("disable")}},
    ]

    const columns = ref<Column[]>([
        {
            dataIndex : 'name',
            title : langStore.translate('name'),
        },

        {
            dataIndex : 'leader',
            title : langStore.translate('leader'),
        },

        {
            dataIndex : 'tel',
            title : langStore.translate('tel'),
        },

        {
            dataIndex : 'sort',
            title : langStore.translate('sort'),
        },

        {
            dataIndex : 'status',
            title : langStore.translate('status'),
        },
        
        {
            dataIndex : '$action',
            title : langStore.translate('operation'),
            align : 'center',
            $edit(row) {
                dialogTitle.value = langStore.translate('edit')
                formFields.forEach(field => {
                    field.defaultValue = row[field.name]
                    if(field.name == 'status') {
                        field.defaultValue = Boolean(row[field.name])
                    }else if(field.name == 'parentId') {
                        field.attrs = {disabled : true}
                    }
                })
                visible.value = true
            },

            async $delete(row, index) {
                const res = await deleteApi(row.id)
                if(res.success) {
                    getList()
                    message.success(langStore.translate('deleteSuccess'))
                }else {
                    message.error(res.msg)
                }
            }
            
        },
    ])

    const dataRows = ref<any[]>([])
   
    const rules = {
        parentId : [
            {
                required : true,
                message : langStore.translate('please.select.superDept')
            }
        ],

        name : [
            {
                required : true,
                message : langStore.translate('please.input.name')
            }
        ]
    }

    async function getOptions() {
        const res = await optionsApi()
        
        if(res.data.length > 0) {
            return recursionFn(res.data, Math.min(...res.data.map(row => row.parentId)), 'id', 'parentId', 'children')
        }

        return []
        
    }

    function getList() {
        listApi().then(res => {
            if(res.data.length > 0) {
                dataRows.value = recursionFn(res.data, Math.min(...res.data.map(row => row.parentId)), 'id', 'parentId', 'children')
            }
            
        })
    }

    function close() {
        formRef.value.resetFields()
        formRef.value.clearValidate()
    }

    function addNew(parent) {
        dialogTitle.value = langStore.translate('add')

        formFields.forEach(field => {
            delete field.defaultValue

            if(field.name === 'parentId'){
                field.attrs = null
                field.defaultValue = parent ? parent.id : ''
            }else if(field.name == 'status') {
                field.defaultValue = true
            }
        })


        visible.value = true
        
    }

    async function submit() {
        let params  = await formRef.value.validate()
        params.status = Number(params.status)
        params.sort = Number(params.sort)
        const res = await saveApi(params)
        if(res.success) {
            getList()
            message.success(langStore.translate('saveSuccess'))
            close()
            visible.value = false
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }


    getList()

</script>